package safe.yunchexing.com.cloudsafe.server;


import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import safe.yunchexing.com.cloudsafe.CloudApplication;
import safe.yunchexing.com.cloudsafe.server.service.UserApiService;

public class RestClient {

    /**
     * 正式地址 *
     */
    private static final String URL_BASE_RELEASE = "http://baidu.com";

    /**
     * Debug地址 *
     */
    private static final String URL_BASE_DEBUG = "http://baidu.com";




    public static final String URL_BASE = CloudApplication.getInstance().isDebug() ? URL_BASE_DEBUG : URL_BASE_RELEASE;

    private static UserApiService userApiService;


    /**
     * get user related API service, for user module API 获取用户相关的API服务,为用户模块API
     *
     * @return
     */
    public static UserApiService getUserApiService(String token) {
        if (userApiService == null) {
            userApiService = createService(UserApiService.class, URL_BASE, token);
        }
        return userApiService;
    }


    /**
     * create service class with header contains token 创建header里面包含token的service
     *
     * @param serviceClass interface class defines APIs
     * @param baseUrl      service base URL
     * @param token        user token
     * @return
     */
    public static <T> T createService(final Class<T> serviceClass, String baseUrl, final String token) {
        OkHttpClient mClient = new OkHttpClient();
        mClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request.Builder request = chain.request().newBuilder();
                request.addHeader("User-Agent", token);

//                if (){
//                    request.addHeader("content-type", "multipart/form-data");
//                }

                Response response = chain.proceed(request.build());
                return response;
            }
        });

       Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(mClient)
                .build();

        T service = mRetrofit.create(serviceClass);
        return service;
    }

    /**
     * 清楚缓存服务
     */
    private static void clearCachedService() {
        userApiService = null;
    }

}
